package com.xiaowei.gym.gymjsp.ware.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import com.xiaowei.gym.gymjsp.ware.entity.AttendanceEntity;
import com.xiaowei.gym.gymjsp.ware.entity.PersonnelEntity;
import com.xiaowei.gym.gymjsp.ware.entity.SalaryEntity;
import com.xiaowei.gym.gymjsp.ware.service.AttendanceService;
import com.xiaowei.gym.gymjsp.ware.service.PersonnelService;
import com.xiaowei.gym.gymjsp.ware.service.SalaryService;
import com.xiaowei.gym.gymjsp.ware.service.impl.AttendanceServiceImpl;
import com.xiaowei.gym.gymjsp.ware.service.impl.PersonnelServiceImpl;
import com.xiaowei.gym.gymjsp.ware.service.impl.SalaryServiceImpl;
import com.xiaowei.gym.gymjsp.ware.util.Constants;
import com.xiaowei.gym.gymjsp.ware.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@WebServlet({"/gymjsp/salary.do","/gymjsp/attendance.do","/gymjsp/personnel.do"})
public class PersonnelServlet extends HttpServlet {

    private SalaryService salaryService;
    private PersonnelService personnelService;
    private AttendanceService attendanceService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");
        String fullPath = req.getRequestURI(); // 获取完整的请求路径
        String contextPath = req.getContextPath(); // 获取应用的上下文路径
        String pathInfo = req.getPathInfo(); // 获取额外的路径信息
        String servletPath = req.getServletPath(); // 获取Servlet的映射路径
        System.out.println(fullPath+"\n"+contextPath+"\n"+servletPath+"\n"+pathInfo);
        if (servletPath.equals("/gymjsp/salary.do")){
            if (method!=null && method.equals("query")){
                this.salaryquery(req,resp);
            }else if (method != null && method.equals("delsalary")) {
                this.delSalary(req,resp);
            }else if (method != null && method.equals("modify")){
                this.getSalaryById(req,resp,"personnel/salarymodify.jsp");
            }else if (method != null && method.equals("modifyexe")){
                try {
                    this.modifySalary(req,resp);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else if (method != null && method.equals("view")){
                this.getSalaryById(req,resp,"personnel/salaryview.jsp");
            }else if (method != null && method.equals("add")){
                this.addSalary(req,resp);
            }
        }else if(servletPath.equals("/gymjsp/attendance.do")){
            if (method!=null && method.equals("query")){
                this.attendancequery(req,resp);
            }else if (method != null && method.equals("view")){
                this.getAttendanceByid(req,resp,"personnel/attendanceview.jsp");
            }else if (method != null && method.equals("modify")){
                this.getAttendanceByid(req,resp,"personnel/attendancemodify.jsp");
            }else if (method != null && method.equals("add")){
                try {
                    this.addAttendance(req,resp);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else if (method != null && method.equals("modifyexe")){
                try {
                    this.attenDanceModify(req,resp);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }else if (servletPath.equals("/gymjsp/personnel.do")){
            System.out.println("personnel.do进来了");
            if (method!=null && method.equals("query")){
                this.personnelquery(req,resp);
            }else if (method!=null && method.equals("getAll")){
                this.personnelgetAll(req,resp);
            }else if (method != null && method.equals("delpersonnel")){
                this.delPersonnel(req,resp);
            }else if (method != null && method.equals("add")){
                this.addPersonnel(req,resp);
            }else if (method != null && method.equals("staffmodify")){
                this.staffByid(req,resp,"personnel/staffmodify.jsp");
            }else if (method != null && method.equals("staffview")){
                this.staffByid(req,resp, "personnel/staffview.jsp");
            }else if (method != null && method.equals("modifyexe")){
                this.staffmodify(req,resp);
            }
        }


    }

    private void attenDanceModify(HttpServletRequest request, HttpServletResponse resp) throws ParseException, IOException, ServletException {
        System.out.println("modify进来了");
        String aid = request.getParameter("aid");
        String time_in = request.getParameter("time_in");
        String time_out = request.getParameter("time_out");
        String[] timeInParts = time_in.split("T");
        String[] timeOutParts = time_out.split("T");
        String formatTimeIn = timeInParts[0]+" "+ timeInParts[1];
        String formatTimeOut = timeOutParts[0]+ " " +timeOutParts[1];
        AttendanceEntity attendanceEntity = new AttendanceEntity();
        attendanceEntity.setId(Integer.valueOf(aid));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        attendanceEntity.setTime_in(dateFormat.parse(formatTimeIn));
        attendanceEntity.setTime_out(dateFormat.parse(formatTimeOut));
        if (attendanceService.modify(attendanceEntity)) {
            resp.sendRedirect(request.getContextPath() + "/gymjsp/attendance.do?method=query");
        } else {
            request.getRequestDispatcher("personnel/attendancemodify.jsp").forward(request, resp);
        }
    }

    private void addAttendance(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, ServletException {
        /**
         * employeeId:
         * 6
         * time_in:
         * 2023-12-13T01:10
         * time_out:
         * 2023-12-13T22:14
         */
        String employeeId = req.getParameter("employeeId");
        String time_in = req.getParameter("time_in");
        String time_out = req.getParameter("time_out");
        String[] timeInParts = time_in.split("T");
        String[] timeOutParts = time_out.split("T");
        String formattimeIn = timeInParts[0]+" "+ timeInParts[1];
        String formattimeOut = timeOutParts[0]+" "+ timeOutParts[1];
        AttendanceEntity attendanceEntity = new AttendanceEntity();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        attendanceEntity.setEmployee_id(Integer.valueOf(employeeId));
        attendanceEntity.setTime_in(simpleDateFormat.parse(formattimeIn));
        attendanceEntity.setTime_out(simpleDateFormat.parse(formattimeOut));
        if (attendanceService.addAttendance(attendanceEntity)){
            resp.sendRedirect(req.getContextPath() + "/gymjsp/attendance.do?method=query");
        }else {
            req.getRequestDispatcher("personnel/attendanceadd.jsp").forward(req, resp);
        }

    }

    private void getAttendanceByid(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        String aid = req.getParameter("aid");
        if (!StringUtils.isNullOrEmpty(aid)){
            AttendanceEntity attendanceEntity = attendanceService.getByid(aid);
            req.setAttribute("attendance", attendanceEntity);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

    private void staffByid(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        String pid = req.getParameter("pid");
        if (!StringUtils.isNullOrEmpty(pid)){
            PersonnelEntity personnelEntity = personnelService.getByid(pid);
            req.setAttribute("personnel", personnelEntity);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

    private void staffmodify(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {

        System.out.println("modify进来了");
        String pid = request.getParameter("pid");
        String name = request.getParameter("personnelname");
        String age = request.getParameter("age");
        String gender = request.getParameter("gender");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String position = request.getParameter("position");
        PersonnelEntity personnelEntity = new PersonnelEntity();
        personnelEntity.setId(Integer.valueOf(pid));
        personnelEntity.setName(name);
        personnelEntity.setAge(Integer.valueOf(age));
        personnelEntity.setGender(gender);
        personnelEntity.setPhone(phone);
        personnelEntity.setAddress(address);
        personnelEntity.setPosition(position);
        System.out.println(personnelEntity);
        if (personnelService.modify(personnelEntity)) {
            resp.sendRedirect(request.getContextPath() + "/gymjsp/personnel.do?method=query");
        } else {
            request.getRequestDispatcher("personnel/staffmodify.jsp").forward(request, resp);
        }
    }

    private void addPersonnel(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String name = req.getParameter("personnelname");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String position = req.getParameter("position");

        PersonnelEntity personnelEntity = new PersonnelEntity();
        personnelEntity.setName(name);
        personnelEntity.setAge(Integer.valueOf(age));
        personnelEntity.setGender(gender);
        personnelEntity.setPhone(phone);
        personnelEntity.setAddress(address);
        personnelEntity.setPosition(position);
        System.out.println(personnelEntity);
        if (personnelService.addPersonnel(personnelEntity)){
            resp.sendRedirect(req.getContextPath() + "/gymjsp/personnel.do?method=query");
        }else {
            req.getRequestDispatcher("personnel/staffadd.jsp").forward(req, resp);
        }
    }

    private void delPersonnel(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        String id = request.getParameter("pid");
        System.out.println("获取到的id:"+id);
        String[] ids = JSON.parseObject(id,String[].class);
        Integer[] delId = new Integer[ids.length];
        try {
            delId = Arrays.stream(ids)
                    .mapToInt(Integer::parseInt)
                    .boxed()
                    .toArray(Integer[]::new);
            System.out.println("delId长度:"+delId.length);
            System.out.println("delId:"+delId.toString());
        } catch (Exception e) {
            // TODO: handle exception
            delId[0] = 0;
        }
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId.length <= 0 ) {
            resultMap.put("delResult", "notexist");
        } else {
            if (personnelService.delPersonnel(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        Gson gson = new Gson();
        outPrintWriter.write(gson.toJson(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();


    }

    private void personnelgetAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        List<PersonnelEntity> personnelAll = personnelService.getPersonnelAll();
        //把providerList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(personnelAll));
        outPrintWriter.flush();
        outPrintWriter.close();

    }

    private void personnelquery(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {

        //从前端获取数据
        String name = request.getParameter("queryName");
//        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<PersonnelEntity> personnelEntityList = null;
        //第一次走这个请求，一定是第一页，页面大小是固定的
        //设置页面容量
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize") == null ? String.valueOf(Constants.pageSize) : request.getParameter("pageSize"));
        if (pageSize == null){
            pageSize = Constants.pageSize;
        }
        //默认当前页码
        int currentPageNo = 1;

        if (name == null) {
            name = "";
        }

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("gymjsp/error.jsp");
            }
        }
        //总数量（表）
        List<PersonnelEntity> personnelAll = personnelService.getPersonnelAll();
        int totalCount = personnelAll.size();
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);  //当前页
        pages.setPageSize(pageSize);            //页面大小
        pages.setTotalCount(totalCount);        //总数量

        int totalPageCount = pages.getTotalPageCount();  //总页面数量

        //控制首页和尾页
        //如果页面小于第一页，就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
            //如果当前页面大于最后一页，当前页等于最后一页即可
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        //获取员工信息列表展示
        personnelEntityList = personnelService.getPersonnelList(name, currentPageNo, pageSize);
        System.out.println(personnelEntityList);
        request.setAttribute("personnel", personnelEntityList);
        request.setAttribute("name",name);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("personnel/staff.jsp").forward(request,resp);
    }

    private void attendancequery(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {

        //从前端获取数据
        String employeeId = request.getParameter("employee_id");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<AttendanceEntity> attendanceEntityList = null;
        //第一次走这个请求，一定是第一页，页面大小是固定的
        //设置页面容量
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize") == null ? String.valueOf(Constants.pageSize) : request.getParameter("pageSize"));
        if (pageSize == null){
            pageSize = Constants.pageSize;
        }
        //默认当前页码
        int currentPageNo = 1;

        if (employeeId == null) {
            employeeId = "";
        }

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("gymjsp/error.jsp");
            }
        }
        //总数量（表）
        int count = attendanceService.getCount();
        int totalCount = count;
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);  //当前页
        pages.setPageSize(pageSize);            //页面大小
        pages.setTotalCount(totalCount);        //总数量

        int totalPageCount = pages.getTotalPageCount();  //总页面数量

        //控制首页和尾页
        //如果页面小于第一页，就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
            //如果当前页面大于最后一页，当前页等于最后一页即可
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        //获取员工信息列表展示
        attendanceEntityList = attendanceService.getattendanceList(employeeId, currentPageNo, pageSize);
        System.out.println(attendanceEntityList);
        request.setAttribute("attendanceList", attendanceEntityList);
        request.setAttribute("employeeId",employeeId);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("personnel/attendance.jsp").forward(request,resp);
    }

    private void salaryquery(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {
        //从前端获取数据
        String employeeId = request.getParameter("employee_id");
//        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<SalaryEntity> salaryEntityList = null;
        //第一次走这个请求，一定是第一页，页面大小是固定的
        //设置页面容量
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize") == null ? String.valueOf(Constants.pageSize) : request.getParameter("pageSize"));
        if (pageSize == null){
            pageSize = Constants.pageSize;
        }
        //默认当前页码
        int currentPageNo = 1;

        if (employeeId == null) {
            employeeId = "";
        }

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("gymjsp/error.jsp");
            }
        }
        //总数量（表）
        int totalCount = salaryService.getSalaryCount();
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);  //当前页
        pages.setPageSize(pageSize);            //页面大小
        pages.setTotalCount(totalCount);        //总数量

        int totalPageCount = pages.getTotalPageCount();  //总页面数量

        //控制首页和尾页
        //如果页面小于第一页，就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
            //如果当前页面大于最后一页，当前页等于最后一页即可
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        //获取工资列表展示
        salaryEntityList = salaryService.getSalaryList(employeeId, currentPageNo, pageSize);
        System.out.println(salaryEntityList);
        request.setAttribute("salaryList", salaryEntityList);
        request.setAttribute("employeeId", employeeId);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("personnel/salary.jsp").forward(request,resp);
    }

    private void modifySalary(HttpServletRequest request, HttpServletResponse resp) throws ParseException, IOException, ServletException {

        System.out.println("modify进来了");
        String sid = request.getParameter("sid");
        String month = request.getParameter("salaryMonth");
        String[] datetimeParts = month.split("T");
        String formatMonth = datetimeParts[0]+" "+ datetimeParts[1];
        String amount = request.getParameter("salaryAmount");
        SalaryEntity salaryEntity = new SalaryEntity();
        salaryEntity.setId(Integer.valueOf(sid));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        salaryEntity.setMonth(dateFormat.parse(formatMonth));
        salaryEntity.setAmount(new BigDecimal(amount));
        if (salaryService.modify(salaryEntity)) {
            resp.sendRedirect(request.getContextPath() + "/gymjsp/salary.do?method=query");
        } else {
            request.getRequestDispatcher("manager/salarymodify.jsp").forward(request, resp);
        }

    }

    private void getSalaryById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        if (!StringUtils.isNullOrEmpty(sid)){
            SalaryEntity salaryEntity = salaryService.getSalaryById(Integer.valueOf(sid));
            req.setAttribute("salary", salaryEntity);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

    private void delSalary(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        String id = request.getParameter("sid");
        System.out.println("获取到的id:"+id);
        String[] ids = JSON.parseObject(id,String[].class);
        Integer[] delId = new Integer[ids.length];
        try {
            delId = Arrays.stream(ids)
                    .mapToInt(Integer::parseInt)
                    .boxed()
                    .toArray(Integer[]::new);
            System.out.println("delId长度:"+delId.length);
            System.out.println("delId:"+delId.toString());
        } catch (Exception e) {
            // TODO: handle exception
            delId[0] = 0;
        }
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId.length <= 0 ) {
            resultMap.put("delResult", "notexist");
        } else {
            if (salaryService.deleteSalaryByIds(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        Gson gson = new Gson();
        outPrintWriter.write(gson.toJson(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();

    }

    private void addSalary(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {
        String employeeId = request.getParameter("employeeId");
        String amount = request.getParameter("Amount");
        SalaryEntity salaryEntity = new SalaryEntity();
        salaryEntity.setEmployee_id(Integer.valueOf(employeeId));
        salaryEntity.setAmount(new BigDecimal(amount));
        salaryEntity.setMonth(new Date());
        int salary = salaryService.createSalary(salaryEntity);
        if (salary > 0) {
            System.out.println(request.getContextPath());
            resp.sendRedirect(request.getContextPath() + "/gymjsp/salary.do?method=query");
        } else {
            request.getRequestDispatcher("personnel/salaryadd.jsp").forward(request, resp);
        }
    }

    private void query(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {


    }

    @Override
    public void init() throws ServletException {
        salaryService = new SalaryServiceImpl();
        personnelService = new PersonnelServiceImpl();
        attendanceService = new AttendanceServiceImpl();
    }
}
